import subprocess
import os
import sys


def run_migration_commands():
    try:
        # 获取当前脚本所在目录
        base_dir = os.path.dirname(os.path.abspath(__file__))
        manage_py = os.path.join(base_dir, "mysite", "manage.py")

        # 检查manage.py是否存在
        if not os.path.exists(manage_py):
            print(f"错误: 找不到manage.py文件 {manage_py}")
            sys.exit(1)

        print(f"Manage.py路径: {manage_py}")

        # 设置工作目录
        work_dir = os.path.join(base_dir, "mysite")

        # 执行makemigrations命令
        print("正在执行 makemigrations 命令...")
        makemigrations_result = subprocess.run(
            [sys.executable, "manage.py", "makemigrations"], cwd=work_dir
        )

        if makemigrations_result.returncode != 0:
            print(
                f"makemigrations 命令执行失败，退出码: {makemigrations_result.returncode}"
            )
            return False

        print("makemigrations 命令执行成功\n")

        # 执行migrate命令
        print("正在执行 migrate 命令...")
        migrate_result = subprocess.run(
            [sys.executable, "manage.py", "migrate"], cwd=work_dir
        )

        if migrate_result.returncode != 0:
            print(f"migrate 命令执行失败，退出码: {migrate_result.returncode}")
            return False

        print("migrate 命令执行成功")
        print("数据库迁移完成！")
        return True

    except KeyboardInterrupt:
        print("\n程序被用户中断")
    except Exception as e:
        print(f"发生错误: {e}")

    return False


if __name__ == "__main__":
    success = run_migration_commands()
    if success:
        print("\n数据库迁移脚本执行完成")
    else:
        print("\n数据库迁移脚本执行失败")
        sys.exit(1)
